package com.survey.Controller;

import com.aliyuncs.exceptions.ClientException;
import com.survey.utils.Result;
import com.survey.utils.SmsDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class MessageLoginController {

    @Resource
    public RedisTemplate redisTemplate;


    @RequestMapping("/sendCode")
    @ResponseBody
    public Result login(String phone, HttpSession session) throws ClientException {
        sendCode(phone);
        session.setAttribute("phone",phone);
        return new Result(Result.CODE_SUCCESS,"验证码发送成功");
    }

    @RequestMapping("/message/login")
    @ResponseBody
    public Result messageLogin(String phone,String code){
        //获取用户输入的验证码
        System.out.println(code);
        boolean flag= checkSmsCode(phone,code);
        if(flag){
            return new Result(Result.CODE_SUCCESS);
        }else{
            return new Result(Result.CODE_FAILURE);
        }
    }

    /**
     * 生成验证码
     * @param phone
     */

    public void sendCode(String phone) throws ClientException {
        System.out.println("手机号："+phone);
        //1.生成一个6位随机数（验证码）
        String smscode = (long) (Math.random() * 1000000)+"";
        System.out.println("验证码："+smscode);
        SmsDemo.sendSms(phone,smscode);
        redisTemplate.boundHashOps("smscode").put(phone,smscode);
    }


    /**
     * 校验验证码
     * @param phone
     * @param code
     * @return
     */
    public boolean checkSmsCode(String phone, String code) {
        //从redis中取出
        String smscode = (String)redisTemplate.boundHashOps("smscode").get(phone);
        if(smscode==null){
            return false;
        }
        if(!smscode.equals(code)){
            return false;
        }
        return true;
    }
}
